package com.suirich.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suirich.bean.Account;
import com.suirich.bean.Product;
import com.suirich.bean.ProductCategories;
import com.suirich.common.Constants;
import com.suirich.common.Page;
import com.suirich.service.ProductCategoriesService;
import com.suirich.service.ProductService;

@Controller
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private ProductCategoriesService productCategoriesService;
    

    @RequestMapping(value="/categories/list",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> categoriesList(Long parentId){
        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
            List<ProductCategories> categoriesList = this.productCategoriesService.getProductCategoriesList(parentId);

            result.put("categoriesList", categoriesList);
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/categories/listTree",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> categoriesListTree(){

        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
            List<ProductCategories> categoriesList = this.productCategoriesService.getProductCategoriesList(0L);
            
            for(ProductCategories rootCategory : categoriesList){
                List<ProductCategories> childCategoriesList = this.productCategoriesService.getProductCategoriesList(rootCategory.getId());
                rootCategory.setCategoriesList(childCategoriesList);
            }

            result.put("categoriesList", categoriesList);
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }
    
    @RequestMapping(value="/categories/create",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> createProductCategories(ProductCategories productCategories){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            Date nowDate = new Date();
            
            productCategories.setCreateDate(nowDate);
            productCategories.setCreateDate(nowDate);
            
            this.productCategoriesService.create(productCategories);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/categories/update",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> updateProductCategories(ProductCategories productCategories){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            ProductCategories originalProductCategories = this.productCategoriesService.read(productCategories.getId());
            if(originalProductCategories != null){
                originalProductCategories.setSubject(productCategories.getSubject());
                originalProductCategories.setDescription(productCategories.getDescription());
                originalProductCategories.setImagePath(productCategories.getImagePath());
                originalProductCategories.setParentId(productCategories.getParentId());
            }
            this.productCategoriesService.update(originalProductCategories);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/categories/top",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> topCategory(ProductCategories productCategories){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            ProductCategories originalProductCategories = this.productCategoriesService.read(productCategories.getId());
            if(originalProductCategories != null){
                originalProductCategories.setUpdateDate(new Date());
            }
            
            this.productCategoriesService.update(originalProductCategories);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }
    
    @RequestMapping(value="/categories/delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> deleteProductCategories(ProductCategories productCategories){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            this.productCategoriesService.delete(productCategories);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/create",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> create(Product product,HttpServletRequest request){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            Date nowDate = new Date();
            product.setCreateDate(nowDate);
            product.setUpdateDate(nowDate);
            
            Account account = new Account();
            account.setId((Long)request.getSession().getAttribute(Constants.USER_ID_IN_SESSION));
            product.setAccount(account);
            
            //解析并设置产品描述信息
            String productReadme = product.getProductReadmeInfo();
            byte[] readme = " ".getBytes();
            try {
                if(productReadme != null && productReadme.length() > 0){
                    readme = productReadme.getBytes("UTF-8");
                    product.setProductReadme(readme);
                }
            } catch (UnsupportedEncodingException e) {
                throw new UnsupportedEncodingException("字符串转字节数组异常！");
            }
            
            this.productService.create(product);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }
    
    @RequestMapping(value="/update",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> update(Product product,HttpServletRequest request){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            Product originalProduct = this.productService.read(product.getId());
            originalProduct.setName(product.getName());
            originalProduct.setNumber(product.getNumber());
            originalProduct.setSpec(product.getSpec());
            originalProduct.setProductCategories(product.getProductCategories());
            originalProduct.setNewRelease(product.getNewRelease());
            originalProduct.setImagePath(product.getImagePath());
            originalProduct.setUpdateDate(new Date());
            //解析并设置产品描述信息
            String productReadme = product.getProductReadmeInfo();
            byte[] readme = " ".getBytes();
            try {
                if(productReadme != null && productReadme.length() > 0){
                    readme = productReadme.getBytes("UTF-8");
                    originalProduct.setProductReadme(readme);
                }
            } catch (UnsupportedEncodingException e) {
                throw new UnsupportedEncodingException("字符串转字节数组异常！");
            }
            
            this.productService.update(originalProduct);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/top",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> top(Product product){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            Product originalProduct = this.productService.read(product.getId());
            if(originalProduct != null){
                originalProduct.setUpdateDate(new Date());
            }
            
            this.productService.update(originalProduct);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }
    
    @RequestMapping(value="/list",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> list(Page page){

        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
            List<Product> productList = this.productService.getProductList(page);
            Long productListCount = this.productService.getProductListCount();

            result.put("productList", productList);
            result.put("productListCount", productListCount);
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/searchProducts",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> searchProducts(String newRelease,Long category,Page page){

        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
            List<Long> categories = null;
            
            if(category != null){
                ProductCategories productCategories = this.productCategoriesService.read(category);
                if(productCategories != null){
                    if(productCategories.getParentId()==0){
                        List<ProductCategories> categoriesList = this.productCategoriesService.getProductCategoriesList(productCategories.getId());
                        
                        if(CollectionUtils.isNotEmpty(categoriesList)){
                            categories = new ArrayList<Long>();
                            for(ProductCategories pc : categoriesList){
                                categories.add(pc.getId());
                            }
                        }
                    }else{
                        categories = new ArrayList<Long>();
                        categories.add(productCategories.getId());
                    }
                }
            }

            List<Product> productList = this.productService.getProductListByCondition(newRelease,categories,page);
            Long productListCount = this.productService.getProductListByConditionCount(newRelease,categories);

            result.put("productList", productList);
            result.put("productListCount", productListCount);
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }
    
    @RequestMapping(value="/delete",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> delete(Product product){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            this.productService.delete(product);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/setNewRelease",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> setNewRelease(Product product){

        Map<String,String> result = new HashMap<String,String>();
        
        try {
        	Product newProduct = this.productService.read(product.getId());
        	newProduct.setNewRelease(product.getNewRelease());
        	
        	this.productService.update(newProduct);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            result.put("setNewRelease", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/detail",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> show(Product product){

        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
        	product = this.productService.read(product.getId());
            product.setProductReadme(null);
            product.setAccount(null);
        	
        	result.put("product", product);
        	result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }

    @RequestMapping(value="/{productId}")
    public String productDetailInfo(@PathVariable(value="productId")Long productId,HttpServletRequest request){

        request.setAttribute("productId", productId);
        
        
        return "/product/productDetailInfo.jsp";
    }
}
